package com.huitone.gddw.controller.analysis.longsms;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.common.excel.CreateExcel;
import com.huitone.gddw.common.excel.Original;
import com.huitone.gddw.common.excel.ServiceType;
import com.huitone.gddw.common.excel.SvrNode;
import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.SendSm;
import com.huitone.gddw.dao.entity.SmLog;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.analysis.longsms.ILongSmsRepService;
import com.huitone.gddw.service.dto.analysis.longsms.LongSmsRecDTO;
import com.huitone.gddw.service.dto.analysis.longsms.LongSmsRepDTO;
import com.huitone.gddw.utils.StringUtils;
import com.huitone.gddw.utils.SysLoginUtil;

/**
 * 超长短信统计
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="longSmsRep")
public class LongSmsRepController extends CommonController {

	private final static Logger LOGGER = Logger.getLogger(LongSmsRepController.class);
	
	@Autowired
	private ILongSmsRepService longSmsRepService;
	
	/**
	 * 查询
	 * @param page
	 * @param request
	 * @return QueryPage
	 */
	@ResponseBody
	@RequestMapping(value="query")
	public QueryPage<LongSmsRepDTO> query(QueryPage<SendSm> page, HttpServletRequest request) {
		super.logType = SmLog.LOGTYPE_SELECT;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]查询超长短信统计";
		QueryPage<LongSmsRepDTO> result = null;
		try {
			page.setParams(getParams(request));
			result = longSmsRepService.selectPage(page);
		} catch (Exception e) {
			LOGGER.error("查询超长短信统计信息出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return result;
	}
	
	/**
	 * 获取参数信息
	 * @param request
	 * @return Map<String, Object>
	 */
	private Map<String, Object> getParams(HttpServletRequest request) {
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
//		String smFrom = request.getParameter("smFrom");
		String serviceCode = request.getParameter("serviceCode");
		String lastLength = request.getParameter("lastLength");
//		String isSmFrom = request.getParameter("isSmFrom");
		String isServiceCode = request.getParameter("isServiceCode");
		
		String svrNode = request.getParameter("svrNode");
		String isSvrNode = request.getParameter("isSvrNode");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("startDate", startDate);
		params.put("endDate", endDate);
//		params.put("smFrom", smFrom);
		params.put("serviceCode", serviceCode);
		params.put("lastLength", lastLength);
//		params.put("isSmFrom", isSmFrom);
		params.put("isServiceCode", isServiceCode);
		
		params.put("svrNode", svrNode);
		params.put("isSvrNode", isSvrNode);
		
		return params;
	}
	
	/**
	 * 导出 Excel
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value="/out-excel", method=RequestMethod.POST)
	public void outExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "超长短信统计信息表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		
//		List<?> list = this.getList(request);
		List<LongSmsRepDTO> list = longSmsRepService.getRecord(params);
		if (null == list || 0 == list.size()) {
			list.add(new LongSmsRepDTO());
		}
		List<Class> listClazz = this.getClazz(request);
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, list, listClazz).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
	
	/**
	 * 获取自定义注解
	 * @param request
	 * @return List<Class>
	 */
	@SuppressWarnings("rawtypes")
	private List<Class> getClazz(HttpServletRequest request) {
		List<Class> listClazz = new ArrayList<Class>();
		String isSvrNode = request.getParameter("isSvrNode");
		String isServiceCode = request.getParameter("isServiceCode");
		if (StringUtils.isNotBlank(isSvrNode) && isSvrNode.equals("1")) {
			listClazz.add(SvrNode.class);
		}
		if (StringUtils.isNotBlank(isServiceCode) && isSvrNode.equals("1")) {
			listClazz.add(ServiceType.class);
		}
		if (null == listClazz || 0 == listClazz.size()) {
			listClazz.add(Original.class);
		}
		return listClazz;
	}
	
	/**
	 * 获取查询结果
	 * @param request
	 * @return List<?>
	 */
//	@SuppressWarnings({ "rawtypes", "unchecked" })
//	private List<?> getList(HttpServletRequest request) {
//		Map<String, Object> params = new HashMap<String, Object>();
//		for (Object name : request.getParameterMap().keySet()) {
//			params.put(name.toString(), request.getParameter(name.toString()));
//		}
//		
//		List list = longSmsRepService.getRecord(params);
//		if (null == list || 0 == list.size()) {
//			String isSmFrom = request.getParameter("isSmFrom");
//			String isServiceCode = request.getParameter("isServiceCode");
//			if (StringUtils.isNotBlank(isSmFrom) && isSmFrom.equals("1")) {
//				if (StringUtils.isNotBlank(isServiceCode) && isServiceCode.equals("1")) {
//					list.add(new LongSmsFromSvrRepDTO());
//				} else {
//					list.add(new LongSmsFromRepDTO());
//				}
//			} else {
//				if (StringUtils.isNotBlank(isServiceCode) && isServiceCode.equals("1")) {
//					list.add(new LongSmsSvrRepDTO());
//				} else {
//					list.add(new LongSmsRepDTO());
//				}
//			}
//			list.add(new LongSmsFromSvrRepDTO());
//		}
//		return list;
//	}
	
	/**
	 * 根据发送日期/业务端/短信类型查询明细
	 * @param sendTimeDate 发送日期
	 * @param svrNode 业务端编码
	 * @param serviceCode 短信类型编码
	 * @return QueryPage<LongSmsRecDTO>
	 */
	@ResponseBody
	@RequestMapping(value="detailPage")
	public QueryPage<LongSmsRecDTO> detailPage(QueryPage<?> page, HttpServletRequest request) {
		try {
			page.setParams(getDetailParams(request));
			QueryPage<LongSmsRecDTO> result = longSmsRepService.detailPage(page);
			return result;
		} catch (Exception e) {
			LOGGER.error("根据发送日期/业务端/短信类型查询明细出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 获取跳转明细的参数信息
	 * @param request
	 * @return Map<String, Object>
	 */
	private Map<String, Object> getDetailParams(HttpServletRequest request) {
		String sendTimeDate = request.getParameter("sendTimeDate");
		String svrNode = request.getParameter("svrNode");
		String serviceCode = request.getParameter("serviceCode");
		String lastLength = request.getParameter("lastLength");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sendTimeDate", sendTimeDate);
		params.put("svrNode", svrNode);
		params.put("serviceCode", serviceCode);
		params.put("lastLength", lastLength);
		return params;
	}
	
}
